import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;

public class Servie {
    static List<Socket> sockets = new ArrayList<>();
    public static void main(String[] args) throws Exception {
        System.out.println("服务器开启");
        System.out.println("服务器后台记录:");
        ServerSocket serverSocket = new ServerSocket(8888);

        while (true){
        Socket socket = serverSocket.accept();
        sockets.add(socket);
        new ServieThread(socket).start();
        }

    }

}
class ServieThread extends Thread{
    Socket socket;

    public ServieThread(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {

            InputStream inputStream = null;
            try {
                while (true){
                    inputStream = socket.getInputStream();

                    DataInputStream dis = new DataInputStream(inputStream);

                    String info = dis.readUTF();
                    System.out.println(socket.getPort()+":  "+info);
                    sendInfo(Servie.sockets,info,socket);
                }

            } catch (IOException e) {
                throw new RuntimeException(e);
            }



    }

    private void sendInfo(List<Socket> sockets, String info,Socket socket2) throws IOException {
        for (Socket socket :
                sockets) {
            if(socket != socket2){
                OutputStream outputStream = socket.getOutputStream();
                DataOutputStream dos = new DataOutputStream(outputStream);
                dos.writeUTF(info);
                dos.flush();
            }

        }
    }
}
